﻿using Abp.AspNetCore;
using Abp.Dependency;
using Batman.Cms.Core.Commands;
using Batman.Cms.Core.Configurations;
using Batman.Cms.Core.Extensions;
using Batman.Cms.Core.Middlewares;
using Batman.Cms.Core.Razor;
using Batman.Cms.Core.Tools;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace Batman.Cms.Core
{
    public static class Startup
    {
        public static void AddBatmanCore(this IServiceCollection services, bool isIdentityServer = false)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);

            // 添加又拍云的配置
            services.AddTransient<UpYunConfigurations>();

            IocManager.Instance.Register<ToolBox, ToolBox>(DependencyLifeStyle.Singleton);
            IocManager.Instance.Register<UpYunTool, UpYunTool>(DependencyLifeStyle.Singleton);
            
            //services.AddLogService();
            services.AddCommandPoolService(options => { });
        }

        public static void AddAuthenticationWithConfig(this IServiceCollection services)
        {
            var env = services.BuildServiceProvider().GetService<IHostingEnvironment>();

            var authenticationInfo = env.GetAuthenticationInfo();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = authenticationInfo.ClientId;
                options.DefaultChallengeScheme = authenticationInfo.ClientId;
            })
            .AddCookie("Cookies") //开启会有Scheme already exists: UserManagement问题存在
            .AddOpenIdConnect(authenticationInfo.ClientId,
                              authenticationInfo.DisplayName,
                              options =>
                              {
                                  options.RequireHttpsMetadata = false;
                                  options.ClientId = authenticationInfo.ClientId;
                                  options.Authority = authenticationInfo.Authority;
                                  options.SaveTokens = true;
                                  
                              });
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="useAuthentication">是否使用权限系统保护</param>
        public static void UseBatmanCore(this IApplicationBuilder app, IHostingEnvironment env, bool useAuthentication = true, bool useAbp = false)
        {
            if (useAbp) app.UseAbp();

            app.UseMiddleware<PluginStaticFileMiddleware>();

            // 异常页面中间件
            app.UseMiddleware<ExceptionHandlingMiddleware>();

            // 使用默认mvc
            app.UseMvcWithDefaultRoute();
        }
    }
}
